package com.zerox.controller;
import com.alibaba.fastjson.JSON;
import com.zerox.domain.TableVO;
import com.zerox.entity.Supplier;
import com.zerox.entity.SysUser;
import com.zerox.service.SysUserService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MutableCallSite;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping(value = "tolist")
    public String toList() {
        return "list";
    }

//    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @GetMapping(value = "/list",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String list(Model model,Integer page, Integer limit,String realName,Integer roleId) throws IOException {
        int count = sysUserService.count(realName, roleId);
        List<SysUser> userList = sysUserService.list(page, limit,realName,roleId);
        model.addAttribute("userList",userList);
        TableVO tableVO = new TableVO(0, count, userList, "");

        String json = JSON.toJSONString(tableVO);

//        response.setContentType("application/json;charset=utf-8");
//
//        response.getWriter().print(json);
        return json;
    }


    @GetMapping(value = "toadd")
    public String toAdd() {
        return "add";
    }

    @PostMapping("/add")
    public String add(HttpServletRequest request,Model model, @Valid SysUser sysUser, BindingResult bindingResult, MultipartFile idPic) throws IOException {
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldError = bindingResult.getFieldErrors();
            for (FieldError fieldError1 : fieldError) {
//                System.out.println(fieldError1.getField()+"Error");
                model.addAttribute(fieldError1.getField()+"Error",fieldError1.getDefaultMessage());
            }
//            处理错误
            return "add";
        }

        if (idPic.getSize()>2000000){
            model.addAttribute("idPicError","文件超过2M不能上传");
            return "add";
        }
        // 指定文件存储的目录
        String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

        if (".jpg.png".indexOf(suffix)==-1){
            model.addAttribute("idPicError","文件格式不正确，不能上传");
            return "add";
        }

        String path = request.getSession().getServletContext().getRealPath("statics")+File.separator+"upload";  // ?
        String fileName = RandomUtils.nextInt(1000000)+"_pic"+suffix;
        File fileTo = new File(path+File.separator+fileName);

        //如果文件不存在就创建
        if (!fileTo.exists()){
            fileTo.mkdirs();
        }
        idPic.transferTo(fileTo);

        sysUser.setIdpicpath(fileName);

        int row = sysUserService.add(sysUser);
        if (row > 0) {
            return "redirect:tolist";
        }
        model.addAttribute("errorMsg","新增失败");
        return "redirect:tolist";
    }



    @GetMapping("/accountExists")
    @ResponseBody
    public String accountExists(String account){
        int sysuper= sysUserService.userByAccount(account);
        if (sysuper >0){
            return "1";
        }
        return "0";
    }




    @GetMapping("/view/{userid}")
    public String view(@PathVariable("userid") Integer id, Model model) {
        SysUser sysUser =  sysUserService.selectUser(id);

        model.addAttribute("sysUser",sysUser);
        return "view";
    }

//    @PostMapping(value = "/view/{userid}", produces = "application/json;charset=utf-8")
//    @ResponseBody
//    public String view(@PathVariable("userid") Integer id, Model model) {
//
//        SysUser sysUser = sysUserService.selectUser(id);
//
//        String json = JSON.toJSONString(sysUser);
//
//        return json;
//    }


    @GetMapping (value = "/view2/{userid}", produces = "application/json;charset=utf-8")
    @ResponseBody
    public SysUser vieww(@PathVariable("userid") Integer id, Model model) {

        return sysUserService.selectUser(id);

    }



    @GetMapping(value = "toview")
    public String toview(){
        return "view";
    }

    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id){
        int row = sysUserService.delete(id);
        return row>0 ? "1":"0";
    }


    @GetMapping (value = "/toupdate/{id}")
    public String selectUser(Model model,@PathVariable("id") Integer id) {
        SysUser sysUser = sysUserService.selectUser(id);
        model.addAttribute(sysUser);
        return "update";
    }


    @PostMapping("/update")
    public String update(@Valid SysUser sysUser,BindingResult bindingResult,Model model){
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println(fieldError.getField() + "Error");
                model.addAttribute(fieldError.getField() + "Error", fieldError.getDefaultMessage());
            }
            // 处理错误
            return "update";
        }
        int result =sysUserService.update(sysUser);

        if (result>0){
            return "redirect:tolist";
        }
        model.addAttribute("errorMsg","修改失败");
        return "update";
    }

}